# -*- coding: utf-8 -*-
"""
Created on Wed Jun 15 18:52:45 2016

@author: Yin Qiaonan
"""

import numpy as np
import operator as op
#import matplotlib.pyplot as plt
from os import listdir

def creatDataSet():
    group = np.array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])
    labels = ['A', 'A', 'B', 'B']
    return group, labels

def classify0(inX, dataSet, labels, k):
    dataSetSize = dataSet.shape[0]     #items number
    diffMat = np.tile(inX, (dataSetSize, 1)) - dataSet    #vector difference
    sqDiffMat = diffMat**2
    sqDistances = sqDiffMat.sum(axis = 1)     #row square sum
    distances = sqDistances**0.5     #distance
    sortedDistIndicies = distances.argsort()     #sort index
    classCount = {}
    for i in range(k):
        voteIlabel = labels[sortedDistIndicies[i]]
        classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
    sortedClassCount = sorted(classCount.items(), key = op.itemgetter(1), reverse = True)
    return sortedClassCount[0][0]

def file2matrix(filename):
    fl = open(filename)
    numberOfColumns = len(fl.readline().strip().split('\t'))
    numberOfLines = len(fl.readlines()) + 1
    fl.close()
    returnMat = np.zeros((numberOfLines, numberOfColumns - 1))     #linenumber (rows) * colnumber-1 (columns)
    classLabelVector = []
    fr = open(filename)
    index = 0
    for line in fr.readlines():
        line = line.strip()     #remove head and end spaces
        listFromLine = line.split('\t')     #return a 4 elements list splitted
        returnMat[index,:] = listFromLine[0:numberOfColumns - 1]     #features
        classLabelVector.append(int(listFromLine[-1]))     #labels
        index += 1
    fr.close()
    return returnMat, classLabelVector

def autoNorm(dataSet):
    minVals = dataSet.min(0)
    maxVals = dataSet.max(0)
    ranges = maxVals - minVals
    normDataSet = np.zeros(np.shape(dataSet))
    m = dataSet.shape[0]
    normDataSet = dataSet - np.tile(minVals, (m, 1))
    normDataSet = normDataSet/np.tile(ranges, (m, 1))
    return normDataSet, ranges, minVals

def datingClassTest():
    hoRatio = 0.1
    datingDataMat, datingLabels = file2matrix('datingTestSet2.txt')
#    plt.scatter(datingDataMat[:,0], datingDataMat[:,2],\
#        15*np.array(datingLabels),np.array(datingLabels))     #take a look
    normMat, ranges, minVals = autoNorm(datingDataMat)
    m = normMat.shape[0]
    numTestVecs = int(m*hoRatio)     #test the first 10%
    errorCount = 0.0
    for i in range(numTestVecs):
        classifierResult = classify0(normMat[i,:], normMat[numTestVecs:m, :],\
            datingLabels[numTestVecs:m], 5)
        print("the classifier came back with: %d, the real answer is: %d"\
            %(classifierResult, datingLabels[i]))
        if classifierResult != datingLabels[i]:
            errorCount += 1.0
        print("the total error rate is: %f" %(errorCount/float(numTestVecs)))

def classifyPerson():
    resultList = ['not at all', 'in small doses', 'in large doses']
    percentTats = float(input("percentage of time spent playing video games?"))
    ffMiles = float(input("frequent flier miles earned per year?"))
    iceCream = float(input("liters of ice cream consumed per year?"))
    datingDataMat, datingLabels = file2matrix('datingTestSet2.txt')
    normMat, ranges, minVals = autoNorm(datingDataMat)
    inArr = np.array([ffMiles, percentTats, iceCream])
    classifierResult = classify0((inArr - minVals)/ranges, normMat, datingLabels, 5)
    print("You will probably like this person:", resultList[classifierResult - 1])

def img2vector(filename):
    returnVect = np.zeros((1, 1024))
    fr = open(filename)
    for i in range(32):     #row
        lineStr = fr.readline()     #read a line each time
        for j in range(32):     #column
            returnVect[0, 32*i+j] = int(lineStr[j])
    fr.close()
    return returnVect

def handwritingClassTest():
    hwLabels = []
    trainingFileList = listdir('digits/trainingDigits')     #files name list
    m = len(trainingFileList)
    trainingMat = np.zeros((m, 1024))
    for i in range(m):
        fileNameStr = trainingFileList[i]     #*_*.txt
        fileStr = fileNameStr.split('.')[0]     #*_*
        classNumStr = int(fileStr.split('_')[0])     #*
        hwLabels.append(classNumStr)
        trainingMat[i, :] = img2vector('digits/trainingDigits/%s' %(fileNameStr))
    testFileList = listdir('digits/testDigits')
    errorCount = 0.0
    mTest = len(testFileList)
    for i in range(mTest):
        fileNameStr = testFileList[i]
        fileStr = fileNameStr.split('.')[0]
        classNumStr = int(fileStr.split('_')[0])
        vectorUnderTest = img2vector('digits/testDigits/%s' %(fileNameStr))
        classifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 3)
        print("the classifier came back with: %d, the real answer is: %d"\
            %(classifierResult, classNumStr))
        if classifierResult != classNumStr:
            errorCount += 1.0
    print("\nthe total error rate is: %f" %(errorCount/float(mTest)))
